package com.cts.tmall.app.controller;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.cts.tmall.app.request.R;
import com.cts.tmall.app.request.SkuRequest;
import com.cts.tmall.biz.service.SkuService;
import com.cts.tmall.com.exception.SystemException;
import com.cts.tmall.com.message.RspCode;
import com.cts.tmall.dal.entity.Sku;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/api/sku")
public class SkuController {

    @Autowired
    SkuService skuService;

    @PostMapping("update")
    public R update(@RequestBody List<SkuRequest> skuRequestList) {
        for (SkuRequest request : skuRequestList) {
            if (request.getPrice() == 0) {
                log.error("价格不能为0");
                throw new SystemException(RspCode.FAILURE_SYSTEM);
            }
        }
        Snowflake snowflake = IdUtil.createSnowflake(1L, 1L);
        for (SkuRequest request : skuRequestList) {
            Sku sku = new Sku();
            BeanUtils.copyProperties(request, sku);
            sku.setId(Long.parseLong(request.getId()));
            if(StrUtil.isBlank(sku.getSku())){
                sku.setSku(String.valueOf(snowflake.nextId()));
            }
            skuService.updateById(sku);
        }
        return R.ok();
    }
}
